#!user/bin/env python3
# -- coding: utf-8 --
# @Createtime：2022/5/20
# @Updatetime：0:01
# @Author：Test008
# @File：myrequests.py
# @Description：封装myrequests
from projectparent.config.baseconfig import Baseconfig
from projectparent.utils.mylogger import logger
import requests


class Requests(object):
    def __init__(self):
        self.logger = logger

    def set_request(self, method, url, params=None, data=None, json=None, headers=None, bussiness=None, **kwargs):
        """
        :param bussiness:
        :param headers:请求头
        :param method:请求方法
        :param url:请求的url
        :param params:get请求参数
        :param data:past请求参数data
        :param json:post请求参数json
        :param kwargs:其他参数
        :return:
        """
        # COMMU_URL = Baseconfig.URL1 + url
        url = Baseconfig.URL2 + url
        if method == 'get':
            try:
                self.logger.debug(f'发送：{bussiness}的get请求,请求地址:{url},请求头：{headers},请求参数:{params}')
                r = requests.get(url=url, params=params, **kwargs, headers=headers, )
                self.logger.debug(f'服务器返回的结果:{r.text}')
                return r
            except Exception:
                logger.error(msg=Exception, exc_info=True)
                raise Exception

        if method == 'post':
            try:
                self.logger.debug(f'发送：{bussiness}的post请求,请求地址:{url},请求头：{headers},请求参数:{data},{json}')
                r = requests.post(url=url, data=data, json=json, headers=headers, )
                self.logger.debug(f'服务器返回的结果:{r.text}')
                return r
            except Exception:
                logger.error(msg=Exception, exc_info=True)
                raise Exception

        if method == 'put':
            try:
                self.logger.debug(f'发送：{bussiness}的put请求,请求地址:{url},请求头：{headers},请求参数:{data},{json}')
                r = requests.put(url=url, headers=headers, json=json)
                self.logger.debug(f'服务器返回的结果:{r.text}')
                return r
            except Exception:
                logger.error(msg=Exception, exc_info=True)
                raise Exception

        if method == 'delete':
            try:
                self.logger.debug(f'发送：{bussiness}的delete请求,请求地址:{url},请求头：{headers},请求参数:{data},{json}')
                r = requests.delete(url=url, data=data, json=json, headers=headers, )
                self.logger.debug(f'服务器返回的结果:{r.text}')
                return r
            except Exception:
                logger.error(msg=Exception, exc_info=True)
                raise Exception


# 测试一下
if __name__ == '__main__':
    R = Requests()
    R.set_request('get', url='/topics', bussiness='获取主题首页')
    data = {
        'accesstoken': '04f434ce-1b98-4da1-9a3d-a309c19c70c6',
        'title': '1111111111111',
        'tab': 'ask',
        'content': '222222222',
    }
    R.set_request(method='post', url='/topics', data=data)
